package demo2

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/go-kit/kit/endpoint"
	transport "github.com/go-kit/kit/transport/http"
	"math/rand"
	"net/http"
)

type InfoDto struct {
	Version string
}

type Limier interface {
	Allow() bool
}

type defaultLimiter struct {
}

func (*defaultLimiter) Allow() bool {
	return rand.Intn(3) == 1
}

func addLimier(limier Limier) endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (response interface{}, err error) {
			if limier.Allow() {
				return next(ctx, request)
			}
			return endpoint.Nop(ctx, request)
		}
	}
}

func Main() {

	var end = func(ctx context.Context, request interface{}) (response interface{}, err error) {
		dto := request.(*InfoDto)
		fmt.Println("version :", dto.Version)
		response = map[string]interface{}{
			"data": map[string]interface{}{
				"version": dto.Version,
			},
		}
		err = nil
		return
	}
	//end = addLimier(&defaultLimiter{})(end)

	before := transport.ServerBefore(func(ctx context.Context, request *http.Request) context.Context {
		fmt.Println("http before")
		return ctx
	})

	// transport  需要将 service+编解码 柔和起来
	hand := transport.NewServer(end, func(i context.Context, req *http.Request) (request interface{}, err error) {
		request = &InfoDto{}
		err = json.NewDecoder(req.Body).Decode(&request)
		return
	}, func(i context.Context, writer http.ResponseWriter, response interface{}) (err error) {
		err = json.NewEncoder(writer).Encode(response)
		return
	}, before)

	http.Handle("/", hand)
	http.ListenAndServe(":8888", nil)
}
